var express = require('express');
var router = express.Router();
var db = require('../db/db.js');
var config = require('../config');
var moment = require("moment");
var jwt = require('jsonwebtoken');
var crypto = require("crypto");
var fs = require('fs');
var path = require('path');
var uuid = require('uuid');
var log = require('../util/logger.js');
var sms = require("../util/sms");
var myutil = require("../util/util");
var path = require('path')

var WechatAPI = require('wechat-api');



var api = new WechatAPI(config.wxgzh.appid, config.wxgzh.secret);




/**
 * 下载图片
 * @group H5
 * @route POST /wxapi/gzh/download
 * @summary 下载图片
 * @param {string} fileurl
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.post("/download", async function (req, res) {


    var fileurl = req.body.fileurl;
    var file = path.join(__dirname, '..' + fileurl);
    //var file = path.join(__dirname, '../public/admin/content/images/alipay.png');

    api.uploadMedia(file, "image", function (err, result) {
        console.log("err", err, result);


        var result = {
            "status": "200",
            "message": "",
            data: result
        }
        res.jsonp(result);

    });

});


const cache = require('memory-cache')
const request = require("request");
var sha1 = require('sha1');
const stringRandom = require('string-random');
/**
 * 配置
 * @group H5
 * @route POST /wxapi/gzh/getsign
 * @summary 配置
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.post('/getsign', function (req, res) {

    console.log("ss", req.body);
    var url = req.body.url;
    // url = "https://mall.tiantong369.com/test.html";


    if (url.indexOf("localhost") == -1) {
        var nonceStr = stringRandom(16);
        var timestamp = Math.floor(Date.now() / 1000);
        var jsapi_ticket = null;
        if (cache.get('ticket')) {
            log.info("进入缓存了");
            jsapi_ticket = cache.get('ticket');

            var obj = {
                nonceStr: nonceStr,
                timestamp: timestamp,
                url: url,
                jsapi_ticket: jsapi_ticket,
                signature: sha1("jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + url)
            };
            res.send(obj)
        } else {
            log.info("没有缓存");
            request('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + config.wxgzh.appid + '&secret=' + config.wxgzh.secret, function (error, response, body) {
                if (!error && response.statusCode == 200) {
                    console.log("body", body);
                    var tokenMap = JSON.parse(body);
                    request('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' + tokenMap.access_token + '&type=jsapi', function (error, resp, json) {
                        if (!error && response.statusCode == 200) {
                            console.log("json", json);
                            var ticketMap = JSON.parse(json);
                            cache.put('ticket', ticketMap.ticket, (1000 * 60 * 60 * 24));  //加入缓存

                            var signature = sha1("jsapi_ticket=" + ticketMap.ticket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + url);

                            var obj = {
                                nonceStr: nonceStr,
                                timestamp: timestamp,
                                url: url,
                                jsapi_ticket: ticketMap.ticket,
                                signature: signature
                            }

                            console.log("obj", obj);
                            res.send(obj)
                        }
                    })
                }
            })
        }
    } else {

        var result = {
            "status": 400,
            "message": "",
        }
        res.jsonp(result);
    }



});

// function test() {
//     var ticket = "HoagFKDcsGMVCIY2vOjf9tM-rfVdEvg4Ep3s-B84vps12RKKt3dy5QDsC2MKpcavGulrbKaMdrbjMc97Sl9rLA";
//     var nonceStr = "eU1QLwYHY1zBylQS";
//     var timestamp = 1609901709;
//     var url = "https://mall.tiantong369.com/test.html";
//     var signature = sha1("jsapi_ticket=" + ticket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + url);
//     console.log("c", signature);
// }

// test();



module.exports = router;